package com.boot.dog.web.security.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.StrUtil;
import com.boot.dog.common.constant.Const;
import com.boot.dog.web.security.handler.AuthenticationFailHandler;
import com.boot.dog.web.security.exception.ValidateCodeException;
import com.boot.dog.common.auth.DogUser;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * @Author: MaxLv
 * @Date: 2019/12/2
 */
@Component
@AllArgsConstructor
public class ValidateCodeFilter extends OncePerRequestFilter {

    private final AuthenticationFailHandler failureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        if (StrUtil.equals(Const.URL_KEY, request.getRequestURI())
                && StrUtil.equalsIgnoreCase(request.getMethod(), Const.POST_KEY)) {
            DogUser userLogin = new DogUser(request.getParameter(Const.USERNAME_KEY));
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(userLogin,
                    request.getParameter(Const.PASSWORD_KEY));
            SecurityContextHolder.getContext().setAuthentication(authRequest);
            try {
                validate(request);
            } catch (ValidateCodeException e) {
                failureHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    private void validate(HttpServletRequest request) {
        String sessionCode = (String) request.getSession().getAttribute(Const.CODE_KEY);
        String code = request.getParameter(Const.CODE_KEY);
        if (StrUtil.isEmpty(sessionCode)) {
            throw new ValidateCodeException("验证码过期");
        }
        if (!StrUtil.equals(sessionCode, code)) {
            throw new ValidateCodeException("验证码错误");
        }
        // request.getSession().removeAttribute(CODE_KEY);
    }

}
